from rest_framework import serializers

from goods.models import GoodsChannel, SKU
from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex
from django_redis import get_redis_connection


class SkuSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    object = SkuSerializer(read_only=True)
    class Meta:
        index_classes = [SKUIndex]
        fields = ('text','object')


class UserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        try:
            sku = SKU.objects.filter(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):
        sku_id = validated_data['sku_id']
        user_id = self.context['request'].user.id
        conn = get_redis_connection('history')

        pl = conn.pipeline()
        # 移除所有该sku_id的记录
        pl.lrem('history_%s'%user_id,0,sku_id)
        # 从左边添加sku_id到redis中
        pl.lpush('history_%s'%user_id,sku_id)
        # 从左到右增加和删除末尾数据
        pl.ltrim('history_%s'%user_id,0,4)

        pl.execute()

        return validated_data














